package com.example.sigar.springoot_sigar.util;

import com.sun.deploy.config.OSType;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * @author 奶茶
 * Created by on 2017/12/28.
 * 获取服务器各种信息 内存 cpu 等使用信息
 */
public class SigarUtil {

    private static Sigar init() throws IOException {
        String path = "/sigar/sigar-amd64-winnt.dll";
        File parentFile = new ClassPathResource(path).getFile().getParentFile();
        String property = System.getProperty("java.library.path");
        if(OSType.isWin()){
            property += ";" + parentFile.getCanonicalPath();
        }
        System.setProperty("java.library.path",property);
        return new Sigar();
    }

    public static void main(String[] args) throws IOException, SigarException {
        Sigar sigar = init();

        Mem mem = sigar.getMem();
        // 内存总量
        System.out.println("内存总量:    " + mem.getTotal() / 1024L + "K av");
        // 当前内存使用量
        System.out.println("当前内存使用量:    " + mem.getUsed() / 1024L + "K used");
        BigDecimal divide = BigDecimal.valueOf(mem.getUsed()).divide(BigDecimal.valueOf(mem.getTotal()), new MathContext(2));
        System.out.println("当前内存使用百分比：" + divide);
    }
}
